<template>
  <div>
    <el-card class="table-card">
      <div slot="header">
        <h3>批量修改到货周期</h3>
      </div>
      <el-row type="flex" justify="end">
        <a class="upload-wrap">
          <el-upload
            :disabled="uploadLoading"
            :show-file-list="false"
            accept=".xlsx"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/supplyarea/import4ModifyArrivalDays`"
            :data="uploadParams"
          >
            <el-tooltip>
              <ul slot="content" class="tooltip">
                <li>导入说明：</li>
                <li>
                  1.根据供应商编码、SKU编码、城市编码、到货周期-现值4列进行数据导入;
                </li>
                <li>2.从表格第二行进行导入数据;</li>
                <li>3.数据源可以通过主供及到货周期列表页面根据条件导出获取;</li>
              </ul>
              <el-button :loading="uploadLoading" type="text" size="large"
                >导入</el-button
              >
            </el-tooltip>
          </el-upload>
        </a>
        <el-button
          v-if="!!recordNo"
          type="text"
          size="large"
          @click="handleSubmit"
          :loading="submitLoading"
          >提交</el-button
        >
        <el-button type="text" size="large" @click="$router.go(-1)"
          >返回</el-button
        >
      </el-row>
      <el-row>
        <el-form
          label-position="left"
          label-width="96px"
          size="mini"
          ref="arrivalTimeForm"
          :model="arrivalTimeForm"
        >
          <el-form-item label="超合同原因：">
						<el-input
							maxlength="200"
							:rows="1"
							type="textarea"
							v-model.trim="arrivalTimeForm.launchReason"
						></el-input>
					</el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <basic-table
          isCustomSort
          showActionCol
          showPagination
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :dataSource="tableInfo.list"
          :pagination="pagination"
          :pageSizes="pageSizes"
          :total="pagination.totalNum"
          :actionRender="tableBtnAction"
          @customSortChange="handleSortTable"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
        >
        </basic-table>
      </el-row>
    </el-card>
    <FooterFields
      :footerFields="footerFields"
      :fieldKeys="{
        pusherName: 'operName',
        pushTime: 'opeTime',
        pusherDeptName: 'operDeptName',
        pusherAreaName: 'operAreaName',
      }"
    />
  </div>
</template>
<script>
import BasicTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import { isResponseSuccess } from '@/utils/bizUtils';
import { TABLE_COLUMNS, TIPS_COLUMN } from './constants';

export default {
  components: {
    BasicTable,
    FooterFields
  },
  data () {
    return {
      uploadLoading: false,
      submitLoading: false,
      arrivalTimeForm: {
        launchReason: ''
      },
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 1000,
        pageSize: 1000
      },
      pageSizes: [100, 1000],
      sortInfo: {
        orderby: '',
        orderbyType: ''
      },
      footerFields: {},
      uploadParams: {},
      recordNo: '',
      apiObj: {
        // 获取列表数据
        getTableListService: {
          url: '/sysback/supplyarea/qeuryArrivalDaysFormDetail',
          type: 'post'
        },
        // 删除
        deleteService: {
          url: '/sysback/supplyarea/deleteArrivalDaysRecordDetail',
          type: 'post'
        },
        // 提交
        submitService: {
          url: '/sysback/supplyarea/commitArrivalDaysRecord',
          type: 'post'
        }
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  watch: {
    recordNo (val) {
      this.uploadParams = {
        recordNo: val
      };
    }
  },
  created () {
    const { recordNo } = this.$route.query;
    this.initTableColumn();
    if (recordNo) {
      this.recordNo = recordNo;
      this.getTableData();
    }
  },
  methods: {
    initTableColumn () {
      this.tableInfo.columns = TABLE_COLUMNS;
    },
    // 渲染表格操作栏按钮
    tableBtnAction (h, { row }) {
      return (
        <div class="table-action">
          <el-button type="text" onClick={() => this.handleDelete(row)}>
            删除
          </el-button>
        </div>
      );
    },
    // 表格排序
    handleSortTable (data) {
      const { prop, order } = data
      let orderbyType = '';
      if (order == 'descending') {
        orderbyType = 'desc';
      } else if (order == 'ascending') {
        orderbyType = 'asc';
      }
      this.sortInfo = {
        orderby: prop,
        orderbyType: orderbyType
      }
      this.getTableData()
    },
    getTableData () {
      if (!this.recordNo) {
        return;
      }
      this.initTableColumn();
      let data = {
        ...this.pagination,
        ...this.sortInfo,
        recordNo: this.recordNo
      };
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableInfo.loading = true;
      ApiRequest(
        this.apiObj.getTableListService.url,
        this.apiObj.getTableListService.type,
        data
      ).then((res) => {
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { recordInfo, recordDetaiInfo } = res.retData;
          const hasErrMsgColumn = this.tableInfo.columns.some(item => item.key == 'errorMessage')
          if (recordInfo.hasErrorMsg && !hasErrMsgColumn) {
            this.tableInfo.columns.unshift(TIPS_COLUMN)
          }
          this.tableInfo.list = recordDetaiInfo.dataList;
          this.pagination.totalNum = recordDetaiInfo.totalNum;
          this.footerFields = recordInfo;
          this.arrivalTimeForm.launchReason = recordInfo.launchReason;
        }
      }).catch(() => {
        this.tableInfo.loading = false;
      });
    },
    // 删除
    handleDelete (row) {
      this.tableInfo.loading = true;
      ApiRequest(
        this.apiObj.deleteService.url,
        this.apiObj.deleteService.type,
        { uuid: row.uuid }
      ).then((res) => {
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          this.$message.success('删除成功')
          this.getTableData();
        }
      });
    },
    // 提交
    handleSubmit () {
      let data = {
        recordNo: this.recordNo,
        launchReason: this.arrivalTimeForm.launchReason
      };
      this.submitLoading = true;
      ApiRequest(
        this.apiObj.submitService.url,
        this.apiObj.submitService.type,
        data
      ).then((res) => {
        this.submitLoading = false;
        if (isResponseSuccess(res)) {
          this.$message.success('提交成功')
          this.$router.push({ name: 'chageFromManageList' });
        }
      });
    },
    // 上传之前
    handleBeforeUpload () {
      this.uploadLoading = true;
    },
    // 上传成功
    handleUploadSuccess (res) {
      this.uploadLoading = false;
      const { retMessage, retData } = res;
      if (isResponseSuccess(res)) {
        this.$message.success('导入成功');
        this.recordNo = retData;
        this.getTableData();
      } else {
        this.$message.error(retMessage || '导入失败');
      }
    },
    // 上传失败
    handleUploadError () {
      this.uploadLoading = false;
      this.$message.error('导入失败');
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableData();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableData();
    }
  }
};
</script>
<style scoped>
.upload-wrap {
  margin-right: 10px;
}
.tooltip li {
  margin-bottom: 5px;
}
</style>
